﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace homework14
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            PopulateTreeView();
            FoldersTreeView.MouseDoubleClick += FoldersTreeView_MouseDoubleClick;
        }

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        private void PopulateTreeView()
        {
            // 使用用户目录路径
            var userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var directoryInfo = new DirectoryInfo(userDirectory);

            FoldersTreeView.Items.Clear();

            var rootNode = new TreeViewItem
            {
                Header = directoryInfo.Name,
                Tag = directoryInfo
            };
            FoldersTreeView.Items.Add(rootNode);

            // 异步填充目录结构以避免UI冻结
            rootNode.Expanded += Folder_Expanded;
            ExpandFolder(rootNode);
        }

        private void Folder_Expanded(object sender, RoutedEventArgs e)
        {
            var item = (TreeViewItem)sender;
            // 只有在该节点第一次展开时才填充子节点
            if (item.Items.Count == 1 && item.Items[0] is string)
            {
                item.Items.Clear();
                DirectoryInfo expandedDir = null;
                if (item.Tag is DirectoryInfo)
                {
                    expandedDir = (DirectoryInfo)item.Tag;
                }
                ExpandFolder(item, expandedDir);
            }
        }

        private void ExpandFolder(TreeViewItem item, DirectoryInfo expandedDir = null)
        {
            if (expandedDir == null && item.Tag is DirectoryInfo)
            {
                expandedDir = (DirectoryInfo)item.Tag;
            }

            if (expandedDir != null)
            {
                try
                {
                    foreach (var directory in expandedDir.GetDirectories())
                    {
                        var subItem = new TreeViewItem()
                        {
                            Header = directory.Name,
                            Tag = directory
                        };
                        subItem.Items.Add("加载中..."); // 占位符
                        subItem.Expanded += Folder_Expanded;
                        item.Items.Add(subItem);
                    }
                    foreach (FileInfo file in expandedDir.GetFiles())
                    {
                        var fileItem = new TreeViewItem() { Header = file.Name, Tag = file };
                        item.Items.Add(fileItem);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    item.Items.Add(new TreeViewItem() { Header = "访问被拒绝" });
                }
            }
        }
        private void FoldersTreeView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var treeViewItem = FindTreeViewItemClicked(e.OriginalSource as DependencyObject);
            if (treeViewItem != null)
            {
                Console.WriteLine($"Clicked on item: {treeViewItem.Header}");  // Debug output
                if (treeViewItem.Tag is FileInfo fileInfo)
                {
                    Console.WriteLine($"It's a file: {fileInfo.FullName}");  // Debug output
                    if (fileInfo.Extension.Equals(".txt", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(fileInfo.FullName) { UseShellExecute = true });
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"无法打开文件: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
        }

        private TreeViewItem FindTreeViewItemClicked(DependencyObject source)
        {
            while (source != null && !(source is TreeViewItem))
                source = VisualTreeHelper.GetParent(source);

            return source as TreeViewItem;
        }

        private void PopulateListView(DirectoryInfo directoryInfo)
        {
            FilesListView.Items.Clear();

            try
            {
                foreach (var dir in directoryInfo.GetDirectories())
                {
                    FilesListView.Items.Add(new ListViewItem { Content = dir.Name });
                }
                foreach (var file in directoryInfo.GetFiles())
                {
                    FilesListView.Items.Add(new ListViewItem { Content = file.Name });
                }
            }
            catch (UnauthorizedAccessException)
            {
                FilesListView.Items.Add(new ListViewItem { Content = "访问被拒绝" });
            }
        }

        // 新增：TreeView项目选择变化事件处理程序
        private void FoldersTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is TreeViewItem selectedItem && selectedItem.Tag is DirectoryInfo directoryInfo)
            {
                PopulateListView(directoryInfo);
            }
        }
    }
}

